﻿#region Copyright & License
//
// Project: Quark Framework
// Project site: http://quark.codeplex.com
// See the copyright statement on the project site for more details.
//
// Licensed to the Apache Software Foundation (ASF) under one or more 
// contributor license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright ownership. 
// The ASF licenses this file to you under the Apache License, Version 2.0
// (the "License"); you may not use this file except in compliance with 
// the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#endregion

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Quark.Framework;
using Quark.Framework.Threading;

namespace Quark.Profiler.Framework
{
    /// <summary>
    /// 需要进行分析测试的活动的基类实现
    /// </summary>
    public abstract class ProfilingActivityBase : IProfilingActivity
    {
        #region Members

        private AtomicBool _isContextualizedIntoProfiler;
        private IProfilingContext _profilingContext;
        //private AtomicBool _lastExcecutionSucceed;
        //private AtomicInt _lastExecutionTicks;
        protected object ProfilingSyncRoot { get; set; }

        #endregion

        #region Constructors

        /// <summary/>
        public ProfilingActivityBase()
        {
            this.ProfilingSyncRoot = new object();
            this._isContextualizedIntoProfiler = new AtomicBool();
            //this._lastExcecutionSucceed = new AtomicBool();
            //this._lastExecutionTicks = new AtomicInt();
        }

        #endregion

        #region 执行方法

        /// <summary>
        /// 执行活动
        /// </summary>
        /// <param name="parameters">活动参数</param>
        /// <param name="requestParams">请求信息</param>
        /// <param name="counter">性能计数</param>
        /// <returns>当前执行是否成功</returns>
        protected abstract bool DoExecute(IDictionary<string, object> parameters, ProfilingRequest requestParams, ProfilingTestActivityCounter counter);

        #endregion

        #region IProfilingActivity 成员

        /// <summary>
        /// 获取分析测试上下文实例，如果执行上下文置入，
        /// 即未调用过<see cref="IProfilingProcedure.Contextualize(IProfilingContext)"/>方法则返回空值
        /// </summary>
        /// <seealso cref="IProfilingProcedure.ProfilingContext"/>
        public virtual IProfilingContext ProfilingContext
        {
            get { return this._profilingContext; }
        }

        /// <summary>
        /// 获取最后一次执行测试是否成功，如果未执行过测试则返回false
        /// </summary>
        //public bool IsLastExecutionSucceed
        //{
        //    get { return this._lastExcecutionSucceed.Value; }
        //    set { this._lastExcecutionSucceed.Value = value; }
        //}

        /// <summary>
        /// 获取最后一次执行测试的耗时(毫秒数)，如果未执行过测试则返回0
        /// </summary>
        //public int LastExecutionTicks
        //{
        //    get { return this._lastExecutionTicks.Value; }
        //    set { this._lastExecutionTicks.Value = value; }
        //}

        /// <summary>
        /// 初始化并将当前活动置入到分析测试环境中
        /// </summary>
        /// <param name="context">分析测试上下文</param>
        /// <seealso cref="IProfilingProcedure.ContextualizeIntoProfiler(IProfilingContext)"/>
        public virtual void ContextualizeIntoProfiler(IProfilingContext context)
        {
            if (context == null) throw new ArgumentNullException("context");
            if (this._isContextualizedIntoProfiler.Value) throw new InvalidOperationException(
                string.Format(System.Globalization.CultureInfo.InvariantCulture, ResProfilerFramework.ProfilingProcedureRecontextualizedEx,
                this.GetHashCode(), this.GetType().FullName));

            lock (this.ProfilingSyncRoot)
            {
                this._profilingContext = context;
                this._isContextualizedIntoProfiler.Value = true;
            }
        }

        /// <summary>
        /// 执行活动
        /// </summary>
        /// <param name="parameters">活动参数</param>
        /// <param name="requestParams">请求信息</param>
        /// <param name="counter">性能计数</param>
        /// <returns>当前执行是否成功</returns>
        public bool Execute(IDictionary<string, object> parameters, ProfilingRequest requestParams, ProfilingTestActivityCounter counter)
        {
            if (counter != null)
            {
                counter.BeginTicks = Environment.TickCount;
            }

            try
            {
                counter.Succeed = this.DoExecute(parameters, requestParams, counter);
                return counter.Succeed;
            }
            finally
            {
                counter.EndTicks = Environment.TickCount;
            }
        }

        #endregion

        #region IDisposable 成员

        /// <summary/>
        public virtual void Dispose()
        {
        }

        #endregion
    }
}
